#include "displaydev.h"


//初始化显示屏
screendev *init_screen(const char *device, int floors)  //floors <5否则出错
{
	screendev *lcd = calloc(1, sizeof(screendev));

	const char *devpath = getenv("DISPLAY");
	if(devpath == NULL)
	{
		devpath = device;
	}
	lcd->fd = open(devpath, O_RDWR);
	if(lcd->fd < 0)
	{
		free(lcd);
		return NULL;
	}
	//获取lcd设备信息
	struct fb_var_screeninfo info;
	int ret = ioctl(lcd->fd, FBIOGET_VSCREENINFO, &info);
	if(ret < 0)
	{
		lcd->xres = 800;
		lcd->yres = 480;
		lcd->px = 4;      //(色深/8)
	}
	else
	{
		lcd->xres = info.xres;
		lcd->yres = info.yres;
		lcd->px = info.bits_per_pixel/8;      //(色深/8)
	}
	//映射
	lcd->screensize = lcd->xres*lcd->yres*lcd->px;
	lcd->mptr = mmap(NULL, lcd->screensize, PROT_READ|PROT_WRITE,
			MAP_SHARED, lcd->fd, 0);
	if(lcd->mptr == (void *) -1)
	{
		exit_screen(lcd);
		return NULL;
	}

	//分配每一层对应的缓存空间
	{
		lcd->floor = 0;
		lcd->floors = floors;
	}
	int i = 0;
	for(i = 0; i < floors; i++)
	{
		lcd->screens[i] = malloc(lcd->screensize);
	}
	return lcd;

}

//释放空间
bool exit_screen(screendev *device)
{
	if(device == NULL)
		return false;
	if(device->mptr != (void*)-1)
	{
		munmap(device->mptr, device->screensize);
	}
	if(device->fd > 0)
	{
		close(device->fd);
	}
	if(device->floors > 0)
	{
		int i = 0;
		for(i=0; i<device->floors; i++)
		{
			free(device->screens[i]);
		}
	}
	free(device);
	return true;

}


//绘制一个像素
bool draw_pixel(screendev *device, int x, int y, unsigned int color)
{
	unsigned int *p = device->mptr;
	p = p+y*device->xres+x;    //定位起始位置
	*p = color;   //一次复制4个字节
}


//绘制一块 pixels传入图片对数据，没有头
bool draw_rect(screendev *device, int x, int y, int w, int h, int *pixels)
{
	unsigned int *p = device->mptr;
	p = p+y*device->xres+x;    //定位起始位置

	int i=0, j=0;
	for(i=0; i<h; i++)
	{
		for(j=0; j<w; j++)
		{
			p[j] = pixels[i*w+j];
		}
		p+=device->xres;
	}
	return true;
}

int main(void)
{
	screendev scr;
	screendev *p =&scr;
	char fd[20] = "/dev/fb0";
	int i=0;
	p = init_screen(fd, i);


	int x=0,y=0;
	for(x=0; x<300; x++)
	{
		for(y=0; y<300; y++)
		{
			draw_pixel(p,x,y,0xffffff);
		}
	}



	FILE *file = fopen("./1.bmp", "r");
	char buf[54];
	int ret = fread(buf, 54, 1, file);
	char tmp[200*100*4];
	int j;
	for(i=99; i>=0; i--)
	{
		for(j=0; j<200; j++)
		{
			fread(tmp+i*200*4+j*4, 3, 1, file);
		}
	}

	int *tmp1 = (int*)tmp;

	draw_rect(p, 300, 300, 200, 100,  tmp1);

	exit_screen(p);

	return 0;
}
